package models

import (
	"encoding/json"

	"github.com/go-playground/validator/v10"
)

var (
	v = validator.New()
)

// Book 结构体定义
type Book struct {
	// grom:"column:isbn;", 具体文档: https://gorm.io/docs/models.html#Fields-Tags
	IsBN uint `json:"isbn" gorm:"primaryKey;column:isbn"`
	BookSpec
}

// 定义该对象映射到数据里 表的名称
func (t *Book) TableName() string {
	return "books"
}

type BookSpec struct {
	Title  string  `json:"title"  gorm:"column:title;type:varchar(200)" validate:"required"`
	Author string  `json:"author"  gorm:"column:author;type:varchar(200);index" validate:"required"`
	Price  float64 `json:"price"  gorm:"column:price" validate:"required"`
	// bool false
	// nil 是零值, false
	IsSale *bool `json:"is_sale"  gorm:"column:is_sale"`
}

func (t *BookSpec) String() string {
	v, _ := json.Marshal(t)
	return string(v)
}

func (t *BookSpec) Validate() error {
	return v.Struct(t)
}
